<template>
  <div id="login">
    <el-form
      :model="userLoginForm"
      :rules="loginRules"
      status-icon
      ref="userLoginFormRef"
      label-position="left"
      label-width="0px"
      class="demo-ruleForm login-page"
    >
      <h2 style="text-align: center">线上招投标系统</h2>
      <el-form-item prop="phoneNumber">
        <el-input
          type="text"
          @keyup.enter.native="handleSubmit"
          v-model="userLoginForm.phoneNumber"
          auto-complete="off"
          placeholder=""
          prefix-icon="el-icon-mobile-phone"
        ></el-input>
      </el-form-item>
      <el-form-item prop="smsCode">
        <el-input
          @keyup.enter.native="handleSubmit"
          type="text"
          v-model="userLoginForm.smsCode"
          auto-complete="off"
          placeholder="验证码"
          prefix-icon="el-icon-lock"
        >
          <template slot="append">
            <el-button
              :disabled="getCodeBtnIsDisable"
              type="primary"
              size="default"
              @click="handleGetCodeBtnClick"
              >{{ getCodeBtnText }}</el-button
            >
          </template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="loginType != 2" style="width: 100%">
        <div style="float: right">
          <el-button
            type="primary"
            class="el-icon-mobile-phone"
            @click="handleSubmit"
            :loading="loading"
            >登录</el-button
          >
          <el-button class="el-icon-refresh" @click="resetForm">重置</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { baseUrl } from "@/config/env";
import request from "@/router/axios";
import { setToken } from "@/util/auth";
import {setStore, getStore} from '@/util/store'

export default {
  data() {
    var checkPhoneNumber = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入手机号码"));
      } else if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(value)) {
        return callback(new Error("手机号码有误，请检查"));
      } else {
        callback();
      }
    };
    return {
      loginType: 0,
      getCodeBtnText: "获取验证码",
      getCodeBtnNum: 60, // 倒计时秒数
      getCodeBtnIsDisable: false,
      isShow: false,
      imgCode: undefined,
      registerQRCodeSrc:
        "https://job-recruitment.oss-cn-chengdu.aliyuncs.com/image/1624503429271/2a1c23c14e0f48a7972128ab2b2f8909-youLoveMeToo.png",
      //表单用户登入数据
      loading: false,
      userLoginForm: {
        username: "",
        password: "",
        phoneNumber: "13083400235",
        smsCode: "",
      },
      checked: false,

      //验证规则
      loginRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 6,
            max: 30,
            message: "长度在 6 到 30 个字符",
            trigger: "blur",
          },
        ],
        phoneNumber: [
          {
            validator: checkPhoneNumber,
            trigger: "blur",
          },
        ],
        smsCode: [
          { required: true, message: "请输入收到的验证码", trigger: "blur" },
          {
            min: 6,
            max: 6,
            message: "验证码长度应该是6位",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.getCookie();
  },
  methods: {
    handleGetCodeBtnClick() {
      this.$refs.userLoginFormRef.validateField("phoneNumber", (valid) => {
        if (valid) {
          return;
        } else {
          this.getCode();
        }
      });
    },

    async getCode() {
      this.getCodeBtnIsDisable = true;
      // const { data: res } = await this.$http.get(
      //   "alisms/sendlogincode?phoneNumber=" + this.userLoginForm.phoneNumber
      // );

      request({
        url: baseUrl + "/api/blade-auth/getSmsCode",
        method: "get",
        // data: row
        params: {
          phoneNumber: this.userLoginForm.phoneNumber,
        },
      })
        .then((res) => {
          console.log("==res==", res);
          if (res.status == 200) {
            var interval = setInterval(() => {
              this.getCodeBtnNum = this.getCodeBtnNum - 1;
              this.getCodeBtnText = this.getCodeBtnNum + "后重新获取";
              if (this.getCodeBtnNum == 0) {
                clearInterval(interval);
                this.getCodeBtnText = "获取验证码";
                this.getCodeBtnIsDisable = false;
                this.getCodeBtnNum = 60;
              }
            }, 1000);
          } else {
            this.$message.info("获取验证码失败");
            this.getCodeBtnIsDisable = false;
          }
        })
        .catch((e) => {
          console.info("e", e);
        });
    },

    //登入提交
    handleSubmit: function () {
      this.$refs.userLoginFormRef.validate((valid) => {
        if (valid) {
          this.success();
        } else {
          return false;
        }
      });
    },
    //重置表单
    resetForm() {
      if (this.loginType == 0) {
        this.userLoginForm.username = "";
        this.userLoginForm.password = "";
        // self.clearCookie();
      } else if (this.loginType == 1) {
        this.userLoginForm.phoneNumber = "";
        this.userLoginForm.smsCode = "";
      }
    },
    //验证成功
    async success() {
      this.loading = true;
      //发起登入请求

      // const { data: res } = await this.$http.post(url);
      request({
        url: baseUrl + "/api/blade-auth/loginByPhoneNumber",
        method: "post",
        data: this.userLoginForm,
      })
        .then((res) => {
          console.log("==res==", res);
          if (res.status == 200) {
            console.log("==res.data.data.accessToken==",res.data.data.accessToken);
            setToken(res.data.data.accessToken);
            setStore({name: 'token', content: res.data.data.accessToken})
            
            console.log("==getStor==",getStore({name: 'token'}));
            // this.$pageRouter.push({path: '/lock'});
            // this.$router.push({path: "/lock"});
            console.log("跳转页面");
            this.$router.push({ path: "/ztbIndex" });
          } else {
            this.$message.info("获取验证码失败");
            this.getCodeBtnIsDisable = false;
          }
        })
        .catch((e) => {
          console.info("e", e);
        });
      // if (res.smsCode == 200) {
      //   this.$message.success("登入成功");
      //   if (this.loginType == 0) {
      //     const self = this;
      //     //判断复选框是否被勾选 勾选则调用配置cookie方法
      //     if (self.checked === true) {
      //       //传入账号名，密码，和保存天数3个参数
      //       self.setCookie(
      //         self.userLoginForm.username,
      //         self.userLoginForm.password,
      //         true,
      //         7
      //       );
      //     } else {
      //       console.log("清空Cookie");
      //       //清空Cookie
      //       self.clearCookie();
      //       // 只记住用户名
      //       self.setCookie(self.userLoginForm.username, "", false, 7);
      //     }
      //     // //与后端请求代码，本功能不需要与后台交互所以省略
      //     // console.log("登陆成功");
      //   }
      //   //保存token
      //   localStorage.setItem("JWT_TOKEN", res.data);
      //   this.getUserInfo();
      // } else {
      //   this.isShow = false;
      //   this.$message.error(res.msg);
      // }
      this.loading = false;
    },

    /**
      获取用户信息
     */
    async getUserInfo() {
      const { data: res } = await this.$http.get("user/info");
      if (res.smsCode !== 200)
        return this.$message.error("获取用户信息失败:" + res.msg);
      this.userInfo = res.data;
      //保存用户
      this.$store.commit("setUserInfo", res.data);
      //跳转到home
      this.$router.push("/home");
    },
    close() {
      this.isShow = false;
    },
    //读取cookie
    getCookie: function () {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下

        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split("="); //再次切割

          //判断查找相对应的值
          if (arr2[0] == "userName") {
            this.userLoginForm.username = arr2[1]; //保存到保存数据的地方
          } else if (arr2[0] == "userPwd") {
            this.userLoginForm.password = arr2[1];
          } else if (arr2[0] == "rememberCheck") {
            if (arr2[1] == "true") {
              this.checked = true;
            } else {
              this.checked = false;
            }
          }
        }
      }
    },
    //清除cookie
    clearCookie: function () {
      this.setCookie("", "", false, -1); //修改2值都为空，天数为负1天就好了
    },
    //设置cookie
    setCookie(c_name, c_pwd, c_rememberCheck, exdays) {
      var exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie
      window.document.cookie =
        "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie =
        "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie =
        "rememberCheck" +
        "=" +
        c_rememberCheck +
        ";path=/;expires=" +
        exdate.toGMTString();
    },

    handleClickTab(tab) {
      this.loginType = tab.index;
    },
  },
  created() {},
};
</script>

<style scoped>
html,
body {
  background: #2d3a4b;
}
.homeBox {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0px;
  background-color: #2d3a4b;
}
.login-container {
  width: 100%;
  height: 100%;
}
#login {
  position: relative;
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0px;
  background-color: #2d3a4b;
}

.login-page {
  position: relative;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  margin: 190px auto;
  width: 370px;
  padding: 40px 35px 15px;
  background: #fff;
  border: 1px solid #eaeaea;
}
label.el-checkbox.rememberme {
  margin: 0px 0px 15px;
  text-align: left;
}
</style>


